package com.rongshu.sendmessage.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.BaseFragment;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.UpDataVersionBean;
import com.rongshu.sendmessage.fragment.CategoryFragment;
import com.rongshu.sendmessage.fragment.HomeFragment;
import com.rongshu.sendmessage.fragment.MyFragment;
import com.rongshu.sendmessage.fragment.SendFragment;
import com.rongshu.sendmessage.fragment.util.FrgManager;
import com.rongshu.sendmessage.util.APKVersionCodeUtils;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.Constant;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.OnTouchListener;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.util.upData.UpDataDialog;
import com.rongshu.sendmessage.util.upData.UpdateManager;
import com.rongshu.sendmessage.view.bottomView.UpDataBottomDialog;
import com.rongshu.sendmessage.view.tableView.FragmentViewPagerAdapter;
import com.rongshu.sendmessage.view.tableView.MainScrollViewPager;
import com.rongshu.sendmessage.view.tableView.TabBarView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;


public class MainActivity extends BaseActivity {

    private static Geocoder geocoder;
    private FragmentManager fm;
    private TabBarView mainTabBarView;
    private MainScrollViewPager mainViewpager;
    private List<Fragment> frgs = new ArrayList<>();
    private FrgManager frgManager;
    private static HomeFragment homeFragment;
    private FragmentViewPagerAdapter fragmentPagerAdapter;
    private LocationManager lm;
    private UpDataVersionBean upBean;
    private UpDataBottomDialog upDataBottomDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=this;
        setContentView(R.layout.activity_main);
        initView();
        requestLocationPermission();
        initData();
    }
    private void initView() {
        mainTabBarView = findViewById(R.id.mainTabBarView);
        mainViewpager = findViewById(R.id.mainViewpager);
        mainTabBarView.setViewPager(mainViewpager);
        fm = getSupportFragmentManager();
        frgManager = new FrgManager(this);
//        boolean locationEnabled = isLocationEnabled();
//        ToastUtils.show(mContext,locationEnabled+"");
//        if (!locationEnabled){
//
//
//        }
        initFragmentView();
        initEvent();
    }
    private void initData() {
        String userId= MyApplication.mSettings.getString(HYContent.UserId,"");
        Map<String, String> param = new HashMap<String, String>();
        param.put("clientType","Android");
        param.put("userId",userId);
        param.put("equipmentNumber", APKVersionCodeUtils.getDivece(mContext));
        param.put("versionName", APKVersionCodeUtils.getVerName(mContext));
        param.put("versionCode",APKVersionCodeUtils.getVerName(mContext));
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        OkGo.<String>post(new HYContent().PHONE_UP_VERSION).params(param).tag("PHONE_UP_VERSION").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body(),false);
                Log.d("user",response.body());
                final int code = jr.getCode();
                if(code > 0) {
                    upBean= JSON.parseObject(JSON.toJSONString(jr.getData()), UpDataVersionBean.class);
                    if (upBean.isUpdate())
                        requestPermission();
                }
            }
            @Override
            public void onError(Response<String> response) {
                ToastUtils.show(mContext,"操作失败");
            }
        });
    }

    /**
     *
     * @param i i==0加载正常，i==1加载更新，非强制更新，i=2强制更新
     */
    private void showUpDataDialog(int i) {
        switch (i){
            case 1:
                showUpDialog();
                break;
            case 2:

                showMustUpDialog();
                break;
            default:
                break;
        }
    }
    /**
     * 展示更新弹框----强制
     */
    private void showMustUpDialog() {
        DialogUtil.showAlertDialog(mContext,"版本更新", "您有新版本请及时更新", new DialogUtil.OnDialogListener<Void>() {
            @Override
            public void onPositiveButtonClick(Void aVoid) {
                goUpDataing(2,upBean);
            }
            @Override
            public void onNegativeButtonClick(Void aVoid) {
                finishApp();
            }
        });
    }
    //state 1非强制2强制
    public void goUpDataing(int state,UpDataVersionBean upData){
//        UpDataDialog upDataDialog=new UpDataDialog(state,upData);
//        upDataDialog.showDialog(mContext);
        UpdateManager manager = new UpdateManager(mContext,null,upData.getAppURL());
        // 检查软件更新
        manager.checkUpdate();
    }

    /**
     * 展示更新弹框----非强制
     */
    private void showUpDialog() {
        DialogUtil.showConfirmDialog(mContext, "版本更新", "您有新版本请及时更新", new DialogUtil.OnDialogListener<Void>() {
            @Override
            public void onPositiveButtonClick(Void aVoid) {
                goUpDataing(1,upBean);
            }

            @Override
            public void onNegativeButtonClick(Void aVoid) {
                finish();
            }
        });
    }

    //滑动拦截器
    private OnTouchListener onHideKeyboardListener;
    public void setOnHideKeyboardListener(OnTouchListener onHideKeyboardListener){
        this.onHideKeyboardListener = onHideKeyboardListener;
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(onHideKeyboardListener != null)
            onHideKeyboardListener.onTouchClick();
        return super.dispatchTouchEvent(ev);
    }
    /**
     * 初始化table和viewpage正常访问应用
     */
    private void initFragmentView() {
        mainTabBarView.setVisibility(View.VISIBLE);
        mainViewpager.setVisibility(View.VISIBLE);
        homeFragment = new HomeFragment();
        frgs.add(homeFragment);
//        CategoryFragment categoryFragment = new CategoryFragment();
//        frgs.add(categoryFragment);
        SendFragment sendFragment = new SendFragment();
        frgs.add(sendFragment);
        MyFragment myFragment = new MyFragment();
        frgs.add(myFragment);
        fragmentPagerAdapter = new FragmentViewPagerAdapter(fm, mainViewpager, frgs);
        mainViewpager.setAdapter(fragmentPagerAdapter);
        mainTabBarView.setViewPager(mainViewpager);
        mainViewpager.setCurrentItem(0);
        mainTabBarView.selectedTabUI(0);

    }
    public boolean isLocationEnabled() {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }
    private void initEvent() {
        mainTabBarView.setOnTabClickListener(new TabBarView.OnTabClickListener() {
            @Override
            public boolean onTabClick(View v) {
                frgManager.popAllFrg();
                return false;
            }
        });
        mainTabBarView.setOnTabSelectedListener(new TabBarView.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                initTabSelect(position);
//                ShowGuidEvent lShowGuidTwoEvent = new ShowGuidEvent();
//                lShowGuidTwoEvent.setIndex(position);
//                EventBus.getDefault().post(lShowGuidTwoEvent);

                Intent intent=new Intent("com.huoyun.tabbar.itemclick");
                intent.putExtra("position",position);
                sendBroadcast(intent);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!MyApplication.mSettings.getBoolean(HYContent.IS_LOGIN,false)){
            finish();
        }
    }

    private void initTabSelect(int position) {
        mainViewpager.setCurrentItem(position);
        mainTabBarView.selectedTabUI(position);
// 获取到Activity下的Fragment
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments == null)
        {
            return;
        }
        // 查找在Fragment中onRequestPermissionsResult方法并调用
        for (int i = 0; i < fragments.size(); i++) {
            Fragment fragment = fragments.get(i);
            if ((fragment instanceof BaseFragment))
            {
                ((BaseFragment)fragment).upData(position);
            }
        }

    }
    //定位
    private void requestLocationPermission() {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_BACKGROUND_LOCATION,
                        Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS},
                        Constant.RETURN_SCAN_RESULT);

            }else{
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS}, Constant.RETURN_SCAN_RESULT);

            }

        }else {
            checkLocation();
        }
    }
    private void checkLocation() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS模块是否开启，如果没有则开启
        if (!locationManager
                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            DialogUtil.showTextDialog(mContext, "请打开GPS", "打开GPS更好的体验应用哦", false, new DialogUtil.OnDialogListener<Void>() {
                @Override
                public void onPositiveButtonClick(Void aVoid) {
                    // 转到手机设置界面，用户设置GPS
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 123); // 设置完成后返回到原来的界面
                }

                @Override
                public void onNegativeButtonClick(Void aVoid) {

                }
            });
        }else{
            getLocation();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==123){
            checkLocation();
        }
    }
    //获取定位信息
    private void getLocation() {
        //初始化定位
        AMapLocationClient mLocationClient = new AMapLocationClient(mContext);
        //设置定位回调监听
        mLocationClient.setLocationListener(aMapLocation -> {

            MyApplication.editor.putString(HYContent.CITY,aMapLocation.getCity()+"");
            MyApplication.editor.putString(HYContent.CITY_CODE,aMapLocation.getCityCode());
            MyApplication.editor.putString(HYContent.Latitude, aMapLocation.getLatitude()+"");
            MyApplication.editor.putString(HYContent.Longitude,aMapLocation.getLongitude()+"");
            MyApplication.editor.putString(HYContent.LOCATION , aMapLocation.getCity()+"  "+aMapLocation.getDistrict());
            MyApplication.editor.putString(HYContent.LA_LO_LOCATION,aMapLocation.getLatitude()+","+aMapLocation.getLongitude()+"");
            MyApplication.editor.commit();

            homeFragment.setLocationCity(aMapLocation.getCity()+"");
        });

        //初始化定位参数
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式、、Hight_Accuracy默认的
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }
    private void requestPermission() {
        int result = ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_DENIED) {//PERMISSION_GRANTED
            String[] permissions = {/*Manifest.permission.WRITE_EXTERNAL_STORAGE,*/
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions((BaseActivity)mContext, permissions, 10);
        } else {
            showUpDataDialog(upBean.isForceUpdate()?2:1);
        }

    }
    //权限申请回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Constant.RETURN_SCAN_RESULT) {
            checkLocation();
            return;
        }
        // 获取到Activity下的Fragment
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments == null)
        {
            return;
        }
        if (requestCode == 10) {
            for (int grantResult : grantResults) {
                if (grantResult == PackageManager.PERMISSION_DENIED) {
                    Toast.makeText(this, "请同意权限后重试", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            showUpDataDialog(upBean.isForceUpdate() ? 2 : 1);
        }
        // 查找在Fragment中onRequestPermissionsResult方法并调用
        for (Fragment fragment : fragments)
        {
            if (fragment != null)
            {
                // 这里就会调用我们Fragment中的onRequestPermissionsResult方法
                fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }

    }

}